package com.glodon.paas.message.adapter;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Don Li
 */
@XmlSeeAlso({StringMapAdapter.Adapter.class, StringMapAdapter.MapElement.class})
public class StringMapAdapter extends XmlAdapter<StringMapAdapter.Adapter, Map<String, String>> {
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "Adapter", namespace = "StringMapAdapter")
    public static final class Adapter {

        List<MapElement> items;

        public Adapter() {
        }

        public Adapter(Map<String, String> map) {
            items = new ArrayList<MapElement>(map.size());
            for (Map.Entry<String, String> entry : map.entrySet()) {
                items.add(new MapElement(entry));
            }
        }
    }

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "MapElement", namespace = "StringMapAdapter")
    public static final class MapElement {
        private String key;
        private String value;

        public MapElement() {
        }

        public MapElement(String key, String value) {
            this.key = key;
            this.value = value;
        }

        public MapElement(Map.Entry<String, String> entry) {
            key = entry.getKey();
            value = entry.getValue();
        }

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }

    @Override
    public Adapter marshal(Map<String, String> map) throws Exception {
        if (map == null) {
            return null;
        }
        return new Adapter(map);
    }

    @Override
    public Map<String, String> unmarshal(Adapter adapter) throws Exception {
        if (adapter == null) return null;

        Map<String, String> map = new HashMap<String, String>(adapter.items.size());
        for (MapElement element : adapter.items) {
            map.put(element.getKey(), element.getValue());
        }
        return map;
    }
}

